package com.library.controller;

import com.library.dto.ApiResponse;
import com.library.dto.BookDTO;
import com.library.entity.Book;
import com.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping
    public ApiResponse<List<Book>> getAllBooks() {
        List<Book> books = bookService.getAllBooks();
        return ApiResponse.success(books);
    }

    @GetMapping("/{id}")
    public ApiResponse<Book> getBookById(@PathVariable Long id) {
        Book book = bookService.getBookById(id);
        if (book == null) {
            return ApiResponse.error("图书不存在");
        }
        return ApiResponse.success(book);
    }

    @GetMapping("/search")
    public ApiResponse<List<Book>> searchBooks(@RequestParam String keyword) {
        List<Book> books = bookService.searchBooks(keyword);
        return ApiResponse.success(books);
    }

    @PostMapping
    public ApiResponse<Book> addBook(@RequestBody @Validated BookDTO bookDTO) {
        Book book = bookService.addBook(bookDTO);
        return ApiResponse.success("图书添加成功", book);
    }

    @PutMapping("/{id}")
    public ApiResponse<Book> updateBook(@PathVariable Long id, @RequestBody @Validated BookDTO bookDTO) {
        Book book = bookService.updateBook(id, bookDTO);
        return ApiResponse.success("图书更新成功", book);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteBook(@PathVariable Long id) {
        bookService.deleteBook(id);
        return ApiResponse.success("图书删除成功", null);
    }

    @PostMapping("/{id}/borrow")
    public ApiResponse<Void> borrowBook(
            @PathVariable Long id,
            @RequestParam String borrowerName,
            @RequestParam String borrowerContact) {
        
        boolean success = bookService.borrowBook(id, borrowerName, borrowerContact);
        if (!success) {
            return ApiResponse.error("借阅失败，图书可能不存在或库存不足");
        }
        return ApiResponse.success("借阅成功", null);
    }

    @PostMapping("/return/{borrowRecordId}")
    public ApiResponse<Void> returnBook(@PathVariable Long borrowRecordId) {
        boolean success = bookService.returnBook(borrowRecordId);
        if (!success) {
            return ApiResponse.error("归还失败，借阅记录不存在或已归还");
        }
        return ApiResponse.success("归还成功", null);
    }
}
